package com.baosight.risk.web.risk;

import com.alibaba.druid.sql.visitor.functions.Char;
import com.baosight.risk.api.riri.IRiriRiskService;
import com.baosight.risk.base.controller.BaseController;
import com.baosight.risk.base.entity.MultipleUpdateStatus;
import com.baosight.risk.common.annotation.Log;
import com.baosight.risk.common.enums.BusinessType;
import com.baosight.risk.common.enums.IntegralType;
import com.baosight.risk.common.result.AjaxResult;
import com.baosight.risk.common.utils.ExcelUtil;
import com.baosight.risk.common.utils.StringUtils;
import com.baosight.risk.service.fltd.entity.FltdProcess;
import com.baosight.risk.service.riri.entity.RiriImpRisk;
import com.baosight.risk.service.riri.entity.RiriRisk;
import com.baosight.risk.service.riri.entity.RiriYyRisk;
import com.baosight.risk.service.riri.vo.RiRiRiskDetailParamVO;
import com.baosight.risk.service.riri.vo.RiRiRiskDetailVO;
import com.baosight.risk.service.riri.vo.RiriRiskVO;
import com.baosight.risk.service.riri.vo.RiskTopThreeVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.ws.rs.core.MediaType;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 类 名: RiriRiskControllera
 * 描 述:
 * 作 者: 黎秋荣
 * 创 建：2019年05月08日
 * 版 本：v2.2.0
 * 历 史: (版本) 作者 时间 注释
 */
@Slf4j
@RestController
@RequestMapping("/risk/riri")
@Api(value = "风控自评", description = "风控自评", produces = MediaType.APPLICATION_JSON)
public class RiriRiskController extends BaseController {

    @Autowired
    private IRiriRiskService ririRiskService;

    /**
     * 根据ID查询
     *
     * @param id
     * @return
     */
    @GetMapping("edit")
    @ApiOperation("根据ID查询")
    public AjaxResult edit(@RequestParam("id") String id) {
        return success(ririRiskService.get(id));
    }

    /**
     * 查询风险识别
     *
     * @param ririRisk
     * @return
     */
    @RequestMapping("list")
    @ApiOperation("查询风险识别")
    @Log(integralType = IntegralType.Type2)
    public AjaxResult select(RiriRiskVO ririRisk) {
        log.info("查询风险识别信息：" + ririRisk.toString());
        return getResultPage(ririRiskService.selectRiriRisk(ririRisk, getUser()));
    }

    /**
     * 查询风险识别
     *
     * @param ririRisk
     * @return
     */
    @RequestMapping("predictList")
    @ApiOperation("查询风险识别")
    @Log(integralType = IntegralType.Type2)
    public AjaxResult predictList(RiriRiskVO ririRisk) {
        log.info("查询风险识别信息：" + ririRisk.toString());
        return getResultPage(ririRiskService.selectPredictRiriRisk(ririRisk, getUser()));
    }


    /**
     * 查询待办风险识别
     *
     * @param ririRisk
     * @return
     */
    @RequestMapping("needDealList")
    @ApiOperation("查询待办风险识别")
    @Log(integralType = IntegralType.Type2)
    public AjaxResult needDealSelect(RiriRiskVO ririRisk) {
        log.info("查询风险识别信息：" + ririRisk.toString());
        return getResultPage(ririRiskService.selectNeedRiriRisk(ririRisk, getUser()));
        //return getResultPage(ririRiskService.selectRiriRisk(ririRisk, getUser()));
    }



    /**
     * 查询一般风险识别
     *
     * @param ririRisk
     * @return
     */
    @RequestMapping("queryRisk")
    @ApiOperation("查询一般风险识别")
    @Log(integralType = IntegralType.Type2)
    public AjaxResult queryRisk(RiriRiskVO ririRisk) {
        log.info("查询风险识别信息：" + ririRisk.toString());
        return getResultPage(ririRiskService.queryRisk(ririRisk, getUser()));
        //return getResultPage(ririRiskService.selectRiriRisk(ririRisk, getUser()));
    }

    /**
     * 查询待办预判风险识别
     *
     * @param ririRisk
     * @return
     */
    @RequestMapping("selectPredict")
    @ApiOperation("查询待办预判风险识别")
    @Log(integralType = IntegralType.Type2)
    public AjaxResult selectPredict(RiriRiskVO ririRisk) {
        log.info("查询待办预判风险识别：" + ririRisk.toString());
        return getResultPage(ririRiskService.selectPredict(ririRisk, getUser()));
        //return getResultPage(ririRiskService.selectRiriRisk(ririRisk, getUser()));
    }

    /**
     * 获取上季度数据==接待办
     *
     * @return
     */
    @GetMapping("getLastQuarter")
    @ApiOperation("获取上季度数据==接待办")
    public AjaxResult getLastQuarter() {
        return success(ririRiskService.getLastQuarter());
    }

    @PostMapping("riskTodo")
    @ApiOperation("风险自评待办查询")
    public AjaxResult riskTodo(@RequestBody RiriRiskVO ririRisk) {
        ririRisk.setStatus("A01");
        return getResultPage(ririRiskService.selectRiriRisk(ririRisk, null));
    }

    /**
     * 保存风险识别信息
     *
     * @param ririRiskList
     * @return
     */
    @PostMapping("save")
    @Log(title = "保存风险识别信息")
    @ApiOperation("保存风险识别信息")
    public AjaxResult saveRiriRisk(@RequestBody List<RiriRisk> ririRiskList) throws Exception {
        if (CollectionUtils.isEmpty(ririRiskList)) {
            log.error("数据有误！");
            return error("数据有误！");
        }
        ririRiskService.saveRisk(ririRiskList);
        return toAjax(ririRiskList.size());

    }

    /**
     * 禁用经营风险事件跟踪
     *
     * @param updateStatus 风险库ID
     * @return
     */
    @PostMapping("deleteRiriImpRisk")
    @Log(title = "禁用经营风险事件跟踪")
    @ApiOperation("禁用经营风险事件跟踪")
    public AjaxResult deleteRiriImpRisk(@RequestBody MultipleUpdateStatus updateStatus) throws Exception {
        if (CollectionUtils.isEmpty(updateStatus.getIds())) {
            log.error("数据有误！");
            return error("数据有误！");
        }
        for (String id : updateStatus.getIds()) {
            RiriImpRisk ririImpRisk = ririRiskService.queryImpById(id);
            // 预留状态不可删除
        }
        return toAjax(ririRiskService.deleteImpById(updateStatus.getIds(),updateStatus.getDeleteFlag(), updateStatus.getDeleteTime(),updateStatus.getDeleteBy()));
    }

    /**
     * 禁用经营投资纪律风险
     *
     * @param updateStatus 风险库ID
     * @return
     */
    @PostMapping("deleteRiriYyRisk")
    @Log(title = "禁用经营投资纪律风险信息")
    @ApiOperation("禁用经营投资纪律风险信息")
    public AjaxResult deleteRiriYyRisk(@RequestBody MultipleUpdateStatus updateStatus) throws Exception {
        if (CollectionUtils.isEmpty(updateStatus.getIds())) {
            log.error("数据有误！");
            return error("数据有误！");
        }
        for (String id : updateStatus.getIds()) {
            RiriYyRisk ririYyRisk = ririRiskService.queryYyById(id);
            // 预留状态不可删除
        }
        return toAjax(ririRiskService.deleteYyById(updateStatus.getIds(), updateStatus.getDeleteFlag(), updateStatus.getDeleteTime(),updateStatus.getDeleteBy()));
    }

    /**
     * 查询待办风险识别
     *
     * @param ririYyRisk
     * @return
     */
    @RequestMapping("queryRiriYyRisk")
    @ApiOperation("查询经营投资纪律风险信息")
    @Log(title = "查询经营投资纪律风险信息")
    public AjaxResult queryRiriYyRisk(RiriYyRisk ririYyRisk) {
        log.info("查询经营投资纪律风险信息：" + ririYyRisk.toString());
        return getResultPage(ririRiskService.queryYyRisk(ririYyRisk, getUser()));

    }

    /**
     * 保存经营投资纪律风险信息
     *
     * @param ririYyRiskList
     * @return
     */
    @PostMapping("saveRiriYyRisk")
    @Log(title = "保存经营投资纪律风险信息")
    @ApiOperation("保存经营投资纪律风险信息")
    public AjaxResult saveRiriYyRisk(@RequestBody List<RiriYyRisk> ririYyRiskList) throws Exception {
        if (CollectionUtils.isEmpty(ririYyRiskList)) {
            log.error("数据有误！");
            return error("数据有误！");
        }
        ririRiskService.saveYyRisk(ririYyRiskList);
        return toAjax(ririYyRiskList.size());

    }

    /**
     * 查询待办风险识别
     *
     * @param ririImpRisk
     * @return
     */
    @RequestMapping("queryRiriImpRisk")
    @ApiOperation("查询经营风险事件跟踪信息")
    @Log(title = "查询经营风险事件跟踪信息")
    public AjaxResult queryRiriImpRisk(RiriImpRisk ririImpRisk) {
        log.info("查询经营投资纪律风险信息：" + ririImpRisk.toString());
        return getResultPage(ririRiskService.queryImpRisk(ririImpRisk, getUser()));

    }

    /**
     * 查询是否存在违反《经营投资纪律》
     *
     * @param process
     * @return
     */
    @PostMapping("queryProcessExt1")
    @ApiOperation("查询是否存在违反《经营投资纪律》信息")
    @Log(title = "查询是否存在违反《经营投资纪律》信息")
    public Map<String, Object> queryProcessExt1(@RequestBody FltdProcess process) {
        log.info("查询是否存在违反《经营投资纪律》信息：" + process.getProcGuid());
        List<FltdProcess> fltdProcesses ;
        fltdProcesses = ririRiskService.queryProcessExt1(process);
        Map<String,Object> map = new HashMap<>();

        //查询为空返回size == 1 包含所有元素都为空
        if (fltdProcesses.stream().anyMatch(obj -> obj instanceof FltdProcess) ) {
            map.put("ext1", fltdProcesses.get(0).getExt1());
            map.put("ext2", fltdProcesses.get(0).getExt2());
            String ext3 = fltdProcesses.get(0).getExt3();
            if (ext3.length() > 2) {
                String substring = ext3.substring(1, ext3.length() - 1);
                String[] strArray = substring.split(",");
                String[] nArray = new String[strArray.length];
                for (int i = 0; i < strArray.length; i++) {
                    nArray[i] = strArray[i].trim();
                }
                map.put("ext3", nArray);
            } else {
                map.put("ext3", new int[0]);
            }
        }

        return map;

    }

    /**
     * 保存经营风险事件跟踪信息
     *
     * @param ririImpRiskList
     * @return
     */
    @PostMapping("saveRiriImpRisk")
    @Log(title = "保存经营风险事件跟踪信息")
    @ApiOperation("保存经营风险事件跟踪信息")
    public AjaxResult saveRiriImpRisk(@RequestBody List<RiriImpRisk> ririImpRiskList) throws Exception {
        if (CollectionUtils.isEmpty(ririImpRiskList)) {
            log.error("数据有误！");
            return error("数据有误！");
        }
        ririRiskService.saveImpRisk(ririImpRiskList);
        return toAjax(ririImpRiskList.size());

    }

    /**
     * 保存是否存在违反《经营投资纪律》
     *
     * @param map
     * @return
     */
    @PostMapping("saveProcessExt1")
    @Log(title = "保存是否存在违反《经营投资纪律》")
    @ApiOperation("保存是否存在违反《经营投资纪律》")
    public AjaxResult saveProcessExt1(@RequestBody Map map) throws Exception {
        FltdProcess process = new FltdProcess();
        process.setProcGuid(map.get("procGuid").toString());
        if (map.containsKey("ext1")) {
            process.setExt1(map.get("ext1").toString());
        }
        if (map.containsKey("ext2")) {
            process.setExt2(map.get("ext2").toString());
        }
        if (map.containsKey("ext3")) {
            process.setExt3(map.get("ext3").toString());
        }
        ririRiskService.saveProcessExt1(process);
        return AjaxResult.success();

    }

    /**
     * 保存下季度预判风险识别信息
     *
     * @param ririRiskList
     * @return
     */
    @PostMapping("importSaveRisk")
    @Log(title = "保存下季度预判风险识别信息")
    @ApiOperation("保存下季度预判风险识别信息")
    public AjaxResult importSaveRisk(@RequestBody List<RiriRisk> ririRiskList) throws Exception {
        if (CollectionUtils.isEmpty(ririRiskList)) {
            log.error("数据有误！");
            return error("数据有误！");
        }
        ririRiskService.importSaveRisk(ririRiskList);
        return toAjax(ririRiskList.size());

    }

    /**
     * 保存风险识别信息
     *
     * @param ririRiskList
     * @return
     */
    @PostMapping("importRisk")
    @Log(title = "引入自评风险识别信息")
    @ApiOperation("引入自评风险识别信息")
    public AjaxResult importRisk(@RequestBody List<RiriRisk> ririRiskList) throws Exception {
        if (CollectionUtils.isEmpty(ririRiskList)) {
            log.error("数据有误！");
            return error("数据有误！");
        }
        ririRiskService.importRisk(ririRiskList);
        return toAjax(ririRiskList.size());

    }

    /**
     * 保存风险识别信息
     *
     * @param ririRisk
     * @return
     */
    @PostMapping("updateRisk")
    @Log(title = "保存风险识别信息")
    @ApiOperation("保存风险识别信息")
    public AjaxResult updateRisk(@RequestBody RiriRisk ririRisk) throws Exception {
        return toAjax(ririRiskService.updateRisk(ririRisk));

    }
    /**
     * 根据IDS查询风险识别信息
     *
     * @return
     */
    @GetMapping("/getByIds")
    @ApiOperation("根据IDS查询风险识别信息")
    public AjaxResult getByIds(@RequestParam("ids") List<String> ids) {
        return getResultPage(ririRiskService.getRiriRiskByIds(ids));
    }

    /**
     * 提交风险识别信息
     *
     * @param ririRiskList
     * @return
     */
    @PostMapping("submitRiriRisk")
    @Log(title = "提交风险识别信息", integralType = IntegralType.Type3)
    @ApiOperation("提交风险识别信息")
    public AjaxResult submitRiriRisk(@RequestBody List<RiriRisk> ririRiskList) {
        if (CollectionUtils.isEmpty(ririRiskList)) {
            log.error("数据有误！");
            return error("数据有误！");
        }
        ririRiskService.submitRiriRisk(ririRiskList);
        return toAjax(ririRiskList.size());

    }


    /**
     * 审核通过数据加入历史表
     *
     * @return
     */
    @PostMapping("addHistory")
    @Log(title = "修改风险库信息", businessType = BusinessType.UPDATE)
    @ApiOperation("审核通过数据加入历史表")
    public AjaxResult addHistory(@RequestBody MultipleUpdateStatus updateStatus) {
        List<String> idss = updateStatus.getIds();
        List<RiriRisk> risks = ririRiskService.getRiriRiskByIds(idss);
        if (idss.size() != risks.size()) {
            log.error("数据有误！");
            return error("数据有误！");
        }
        return toAjax(ririRiskService.addHistory(idss));
    }

    /**
     * 禁用风险自评
     *
     * @param updateStatus 风险库ID
     * @return
     */
    @PostMapping("delete")
    @Log(title = "禁用风险识别", businessType = BusinessType.DELETE)
//    @RequiresPermissions("risk:riri:delete")
    @ApiOperation("禁用风险自评")
    public AjaxResult delete(@RequestBody MultipleUpdateStatus updateStatus) throws Exception {
        if (CollectionUtils.isEmpty(updateStatus.getIds())) {
            log.error("数据有误！");
            return error("数据有误！");
        }
        for (String id : updateStatus.getIds()) {
            RiriRisk ririRisk = ririRiskService.get(id);
            if (!"A01".equals(ririRisk.getStatus())) {
                log.error("只有待填报状态可以删除！");
                return error("只有待填报状态可以删除！");
            }
        }
        return toAjax(ririRiskService.deleteById(updateStatus.getIds(), updateStatus.getStatus(), updateStatus.getStatusName()));
    }

    /**
     * 根据IDS查询风险识别信息
     *
     * @return
     */
    @GetMapping("/carryForward")
    @ApiOperation("流转上一年的风险自评数据")
    public AjaxResult carryForward(@RequestParam("acctYear") String acctYear, @RequestParam("quarterCurrent") String quarterCurrent) {
        try {
            ririRiskService.doCarryForward(acctYear, quarterCurrent);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success();
    }

    /**
     * 首页获取topThree数据
     *
     * @param
     * @return
     */
    @RequestMapping("topThree")
    @ApiOperation("首页风险自评top3")
    public AjaxResult queryTopThree(@RequestBody RiskTopThreeVO riskTopThree) {
        if (StringUtils.isEmpty(riskTopThree.getDepartmentClass())) {
            return error("部门类别不能为空！");
        }
        return getResultPage(ririRiskService.selectTopThree(riskTopThree));
    }

    /**
     * 新增校验topThree数据
     * @param ririRisk
     * @return
     */
    @RequestMapping("getTopThree")
    @ApiOperation("风险自评top3")
    public AjaxResult getTopThree(@RequestBody RiriRisk ririRisk) {
        return getResultPage(ririRiskService.getTopThree(ririRisk));
    }

    /**
     * 查询待办风险识别
     * @param ririRisk
     * @return
     */
    @RequestMapping("queryImportantRiskData")
    @ApiOperation("查询待办风险识别")
    public AjaxResult queryImportantRiskData(RiriRiskVO ririRisk) {
        log.info("查询风险识别信息：" + ririRisk.toString());
        return getResultPage(ririRiskService.queryImportantRiskData(ririRisk));
    }




    /**
     * 导出excel
     *
     * @return
     */
    @PostMapping("export")
    @ApiOperation("导出风险识别")
    public AjaxResult exportExcel(@RequestBody RiriRiskVO ririRisk) {
        log.info("导出风险识别信息：" + ririRisk.toString());
        ExcelUtil<RiriRisk> excel = new ExcelUtil<>(RiriRisk.class);
        ririRisk.setExt4("导出");

        //return excel.exportExcel(ririRiskService.selectRiriRisk(ririRisk, getUser()), "风险自评", ririRisk.getColumNameList());
        return excel.exportExcel(ririRiskService.exportExcelRiriRisk(ririRisk, getUser()), "风险自评", ririRisk.getColumNameList());
    }


    /**
     * 导出excel
     *
     * @return
     */
    @PostMapping("exportRisk")
    @ApiOperation("导出一般经营风险事件")
    public AjaxResult exportRisk(@RequestBody RiriRiskVO ririRisk) {
        log.info("导出一般经营风险事件：" + ririRisk.toString());
        ExcelUtil<RiriRisk> excel = new ExcelUtil<>(RiriRisk.class);
        ririRisk.setExt4("导出");
        ririRisk.setDetailType("YY98");

        //return excel.exportExcel(ririRiskService.selectRiriRisk(ririRisk, getUser()), "风险自评", ririRisk.getColumNameList());
        return excel.exportExcel(ririRiskService.exportExcelRiriRisk(ririRisk, getUser()), ririRisk.getAcctYear()+"年度第"+ririRisk.getQuarterCurrent()+"季度"+"一般经营风险事件", ririRisk.getColumNameList());
    }



    /**
     * 导出excel
     *
     * @return
     */
    @PostMapping("exportYy")
    @ResponseBody
    @ApiOperation("导出经营投资纪律")
    public AjaxResult exportYyExcel(@RequestBody Map map) {
        RiriYyRisk ririYyRisk = new RiriYyRisk();
        ririYyRisk.setAcctYear(map.get("acctYear").toString());
        ririYyRisk.setColumNameList((List<String>) map.get("columNameList"));
        ririYyRisk.setManageCompCode(map.get("manageCompCode").toString());
        ririYyRisk.setQuarterCurrent(map.get("quarterCurrent").toString());
        log.info("导出经营投资纪律信息：" + ririYyRisk.toString());
        ExcelUtil<RiriYyRisk> excel = new ExcelUtil<>(RiriYyRisk.class);
        ririYyRisk.setExt4("导出");

        //return excel.exportExcel(ririRiskService.selectRiriRisk(ririRisk, getUser()), "风险自评", ririRisk.getColumNameList());
        return excel.exportExcel(ririRiskService.queryYyRisk(ririYyRisk, getUser()), map.get("acctYear").toString()+"年度第"+map.get("quarterCurrent").toString()+"季度"+"违反经营投资纪律情况", ririYyRisk.getColumNameList());
    }

    /**
     * 导出excel
     *
     * @return
     */
    @PostMapping("exportImp")
    @ResponseBody
    @ApiOperation("导出重大、重要经营风险事件表")
    public AjaxResult exportYyExcel(@RequestBody RiriImpRisk ririImpRisk) {
        log.info("导出重大、重要经营风险事件表：" + ririImpRisk.toString());
        ExcelUtil<RiriImpRisk> excel = new ExcelUtil<>(RiriImpRisk.class);
        ririImpRisk.setExt4("导出");

        //return excel.exportExcel(ririRiskService.selectRiriRisk(ririRisk, getUser()), "风险自评", ririRisk.getColumNameList());
        return excel.exportExcel(ririRiskService.queryImpRisk(ririImpRisk, getUser()), ririImpRisk.getAcctYear()+"年度第"+ririImpRisk.getQuarterCurrent()+"季度"+"重大、重要经营风险事件", ririImpRisk.getColumNameList());
    }

    @PostMapping("updateRowOrder")
    @ApiOperation("排序")
    public AjaxResult updateRowOrder(@RequestBody RiriRiskVO ririRisk){
        ririRiskService.updateRowOrder(ririRisk, getUser());
        return success();
    }



    @PostMapping("exportExcelTop3")
    @ResponseBody
    @ApiOperation("导出各单位风险识别top3")
    public AjaxResult exportExcelTop3(@RequestBody RiskTopThreeVO riskTopThree) throws Exception {
        ExcelUtil<RiriRisk> excel = new ExcelUtil<>(RiriRisk.class);
        riskTopThree.setExt4("导出");
        return excel.exportExcel(ririRiskService.selectTopThree(riskTopThree), "风险自评各单位top3", riskTopThree.getColumNameList());

    }

    @GetMapping("getRiRiRiskDetails")
    @ApiOperation("查询风险自评填报情况")
    public AjaxResult getRiRiRiskDetails(RiRiRiskDetailParamVO vo) {
        startPage();
        return getResultPage(ririRiskService.selectRiRiRiskDetails(vo));
    }


    @PostMapping("changeTop3")
    @ApiOperation("查询风险自评填报情况")
    public AjaxResult changeTop3(@RequestBody RiriRisk ririRisk) throws Exception {
        return toAjax(ririRiskService.updateTop3(ririRisk));
    }

    @PostMapping("importantRiskUpdate")
    @ApiOperation("是否重点风险保存")
    public AjaxResult importantRiskUpdate(@RequestBody RiriRisk ririRisk) throws Exception {
        return toAjax(ririRiskService.importantRiskUpdate(ririRisk));
    }



}
